package server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import cmdparse.CommandParse;


public class ScpServer {
	public static void main(String[] args) throws IOException {
		ServerSocket server = new ServerSocket(9876);
		
		while(true){
			Socket socket = server.accept();
			InputStream in = socket.getInputStream();
			OutputStream out = socket.getOutputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(in));
			out.write("Please input your command:\n".getBytes());
			
			String command = reader.readLine();

			String[] cmd = CommandParse.cmdSplit(command);
			while(cmd == null){
				out.write("Error command!Please input the command:\r\n".getBytes());
				command = reader.readLine();
				cmd = CommandParse.cmdSplit(command);
			}

			out.write("200OK\n".getBytes());
			

			String filename = CommandParse.getFilename(cmd[2]);
			filename = filename.substring(1);
			File file = new File(filename);

			BufferedWriter writer = new BufferedWriter(new FileWriter(file));
			String tip = null;
			while (!"finished".equals(tip = reader.readLine())) {
				writer.write(tip + "\n");
			}
			writer.close();

			
			reader.close();
			in.close();
			out.close();
			socket.close();
		}
	}
}
